define(['template/picture/indexTpl','wx','wx.ajax','wx.tpl','wx.pop','wx.upload','vendor/jquery.ztree.all-3.5','vendor/masonry.pkgd'],function(tpl,wx){
    var page = {};
    var isWrite;
    function init(id,w){
        isWrite = w;
        var t = new Date().getTime();
        $.when(
            $.ajax('/res/css/picture.css?_='+t),
            $.ajax('/res/css/zTreeStyle.css')
        ).done(function(resCss,ztreeCss){
            $('<style type="text/css">').append(resCss[0],ztreeCss[0]).appendTo('head');
            wx.sendData('/resource/all','type=2',initTree);
        });
	}

    function initTree(data){
        for (var i = data.result.length - 1; i >= 0; i--) {
            data.result[i].isParent = data.result[i].isParent == '1' ?true:false;
        }
        $('#window-frame-picture').html(tpl.container);
        $('#window-bar-picture').html('<marquee>使用说明：按住ctrl点击文件夹为查看全部图片</marquee>');

        var setting = {
            view: {
                showLine: true,
                selectedMulti: false
            },
            data: {
                simpleData: {
                    enable:true,
                    idKey: "id",
                    pIdKey: "pId",
                    rootPId: ""
                },
                keep:{
                    leaf:true,
                    parent:true
                }
            },
            edit: {
                enable: true,
                editNameSelectAll: true,
                showRemoveBtn: showRemoveBtn,
                drag: {
                    isCopy:true,
                    autoExpandTrigger: true
                }
            },
            callback: {
                onClick:Onclick,
                onDblClick:OnDdClick,
                onMouseDown: OnMouseDown,
                onRightClick: OnRightClick,
                beforeRemove: beforeRemove,
                beforeDrag: beforeDrag,
                beforeDrop: beforeDrop,
                onRemove: OnRemove,
                onRename: OnRename
            }
        };
        $.fn.zTree.init($('#Js-picture-list'), setting,data.result);

        $('#Js-container,#Js-picture-list,#Js-picture-body').height($('#window-frame-picture').height()-10);

        require(['vendor/ueditor/third-party/zeroclipboard/ZeroClipboard'],function(){
            ZeroClipboard.config({swfPath: "/res/js/vendor/ueditor/third-party/zeroclipboard/ZeroClipboard.swf" });
        });
    }

    function showRemoveBtn(treeId, treeNode) {
        if(treeNode.children)
            return false;
        else
            return true;
    }

    function Onclick(event, treeId, treeNode,clickFlag,dd){
        if(clickFlag === 0){
            if(treeNode.isParent){
                wx.sendData('/resource/get-children','pId='+treeNode.id,function(data){
                    $('#Js-picture-body').html(wx.tpl(tpl.picGrounp,data));
                    $('.grid').masonry({
                      itemSelector: '.grid-item',
                      "gutter": 10
                    });
                    $('.grid-item').mouseenter(function(event) {
                        $('.grid-item i').hide();
                        $(this).find('i').show();
                        setTimeout(function(){$('.grid-item i').hide();},2000);
                    });
                    var client = new ZeroClipboard($('.grid-item i'));
                    client.on("copy", function (event) {
                        event.clipboardData.setData("text/plain", $(event.target).data('src'));
                        $('#window-bar-picture').html('地址拷贝成功！');
                        setTimeout(function(){$('#window-bar-picture').html('');},3000);
                    });
                });
            }
        }
    }

    function OnMouseDown(event, treeId, treeNode) {
        if(treeNode){
            if(!treeNode.modify_by) return;
            var info = '上次修改人：'+treeNode.modify_by+'&nbsp;&nbsp;&nbsp;&nbsp;     修改时间：'+treeNode.modify_time+'&nbsp;&nbsp;&nbsp;&nbsp; | &nbsp;&nbsp;&nbsp;&nbsp;'+'创建人：'+treeNode.create_by+'&nbsp;&nbsp;&nbsp;&nbsp;     创建时间：'+treeNode.create_time;
            $('#window-bar-picture').html(info);
        } else {
            $.fn.zTree.getZTreeObj("Js-picture-list").cancelSelectedNode();
        }
    }

    function OnDdClick(event, treeId, treeNode){
        if(treeNode && !treeNode.isParent){
            $('#Js-picture-body').html(tpl.pictureLoading);
            wx.sendData('/resource/content','id='+treeNode.id,function(data){
                wx.imgLoad(data.result.content,function(w,h){
                    var containerW = $('#Js-picture-body').width();
                    $('#Js-picture-body').html(wx.tpl(tpl.picture,{containerW:containerW,w:w,h:h,path:data.result.content}));
                    wx.upload($('#Js-replace'));
                    $('#Js-replace').on('upload',function(event,imgData){
                        $('#Js-picture-show').attr('src',imgData.result[0].path+'?'+(new Date().getTime()));
                    });
                    var client = new ZeroClipboard($('#Js-copy'));
                    client.on( "copy", function (event) {
                        event.clipboardData.setData("text/plain", $(event.target).data('src'));
                        $('#window-bar-picture').html('地址拷贝成功！');
                        setTimeout(function(){$('#window-bar-picture').html('');},3000);
                    });
                });
            });
        }
    }

    function OnRightClick(event, treeId, treeNode){
        $('#Js-picture-contextmenu').remove();
        var zTree = $.fn.zTree.getZTreeObj("Js-picture-list");
        var uploading = false;
        zTree.selectNode(treeNode);
        if(treeNode && treeNode.isParent){
            event.isUpload = true;
            $('body').append(wx.tpl(tpl.contextmenu,event));
            wx.upload($('#Js-picture-contextmenu').find('input[name="file"]'));
        } else {
            event.isUpload = false;
            $('body').append(wx.tpl(tpl.contextmenu,event));
        }

        $('#Js-picture-addCate').one('click',function(event) {
            createNode(event,1,treeId, treeNode);
            $('#Js-picture-contextmenu').remove();
        });

        $('#Js-picture-contextmenu input[name="file"]').on('upload:before',function(){
            $.load();
            $('#window-bar-picture').html('生在准备上传...');
        }).on('upload:progress',function(event,data){
            $('#window-bar-picture').html('已经上传了'+data+'%');
        }).on('upload',function(event,data){
            if (data.status) {
                $.succ('上传成功');
                $('#window-bar-picture').html('上传完成');
                setTimeout(function(){$('#window-bar-picture').html('');},2000);
                for(var i=0;i<data.result.length;i++){
                    createNode(event,0,treeId, treeNode,data.result[i].path,data.result[i].name);
                }
                $('#Js-picture-contextmenu').remove();
            } else{
                $.fail('上传失败');
            }
        }).on('click',function(e){
            uploading = true;
        });
        $("body").one("click", function(){
            if(!uploading)
                $('#Js-picture-contextmenu').remove();
        });
    }

    function beforeDrop(treeId, treeNodes, targetNode, moveType, isCopy) {
        wx.sendData('resource/move','id='+treeNodes[0].id+'&targetId='+targetNode.id);
        return true;
    }
    function beforeDrag(treeId, treeNodes) {
        // if(treeNodes[0].isParent)
        //     return false;
        // else
            return true;
    }

    function OnRename(event, treeId, treeNode, isCancel) {
        wx.sendData('/resource/rename','id='+treeNode.id+'&name='+treeNode.name);
    }

    function OnRemove(event, treeId, treeNode, isCancel) {
        wx.sendData('/resource/remove','id='+treeNode.id);
    }

    function beforeRemove(treeId, treeNode) {
        return confirm("确认删除 " + treeNode.name + " 吗？");
    }

    function createNode(event,type,treeId,treeNode,content,name){
        var pId = treeNode?treeNode.id:0;
        var name = name?'&name='+name:'';
        var content = content?'&content='+content:'';
        wx.sendData('/resource/create','type=2&isParent='+type+'&pId='+pId+content+name,function(data){
            add(event,data.result,type);
        });
    }

    function add(event,data,type){
        var name = data.name || '新节点'+data.id;
        var zTree = $.fn.zTree.getZTreeObj("Js-picture-list"),
        isParent = type,
        nodes = zTree.getSelectedNodes(),
        treeNode = nodes[0];
        if (treeNode) {
            treeNode = zTree.addNodes(treeNode, {id:data.id, pId:treeNode.id, isParent:isParent, name:name});
        } else {
            treeNode = zTree.addNodes(null, {id:data.id, pId:0, isParent:isParent, name:name});
        }
        if (treeNode && isParent) {

            zTree.editName(treeNode[0]);
        } 
        // else {
        //     alert("叶子节点被锁定，无法增加子节点");
        // }
    }

    function onBodyMouseDown(){
        setTimeout(function(){
            $('#Js-picture-contextmenu').remove();
        },100);
    }

    page.init = init;
    return page;
});